#include <pic18fregs.h>

#pragma config OSC=HS, PWRT=OFF, BOR=OFF, WDT=OFF, CCP2MUX=OFF, LVP=OFF, CP0=OFF , CP1=OFF, CP2=OFF, CP3=OFF


void usart_init() __naked {
	TRISCbits.TRISC7=1; //Make UART RX pin input
	TRISCbits.TRISC6=0; //Make UART TX pin output

        SPBRG=51;     //9600@16MHz Osc

	TXSTAbits.BRGH=1;
	TXSTAbits.SYNC=0;
	RCSTAbits.SPEN=1;
	RCSTAbits.CREN=1;

	TXSTAbits.TXEN=0;
	TXSTAbits.TXEN=1;
	PIE1bits.RCIE=0;
	PIE1bits.TXIE=0;
	PIR1bits.RCIF=0;
	__asm RETURN __endasm;
}

unsigned char usart_recv(unsigned char ds) {
	
	while(ds){
		T1CON = 0x3C;
		TMR1H = 60;             
		TMR1L = 176;    
		PIR1bits.TMR1IF=0;
		T1CONbits.TMR1ON=1;
		while(!PIR1bits.RCIF && !PIR1bits.TMR1IF);
		if(PIR1bits.RCIF) {
			T1CONbits.TMR1ON=0;
			return RCREG;
		} else {
			PIR1bits.TMR1IF=0;
		}
		ds--;
	}
	return 0xFF;

}

void usart_send(unsigned char c) {
	while(!PIR1bits.TXIF);
	TXREG=c;
}


void main()  {
	unsigned char c;
	usart_init();
	
	while(1) {
		c=usart_recv(50);
		usart_send(c);
		
	}
}

